<?php
/**
 * 设计师服务亮点控制器
 */
namespace Beerus\Modules\Designer\Controllers;

use App\Http\Controllers\Controller;
use Doraemon\cache\DesignerAreaRedis;
use Doraemon\model\AdmDesignerArea;
use Encore\Admin\Facades\Admin;
use Encore\Admin\Widgets\Form;
use Hhz\AdministrativeRegion\Region;
use Illuminate\Http\Request;
use Encore\Admin\Grid;
use App\Pockets\GridDataModel as pGridDataModel;
use Encore\Admin\Layout\Content;
use Encore\Admin\Widgets\Tab;
use Illuminate\Support\MessageBag;

class DesignerAreaController extends Controller
{
    const PAGE_SIZE = 20;

    public function __construct()
    {
        parent::__construct();
        Admin::script('$(".pjax-container").attr("id","pjax-container");');
    }

    // 对话列表
    public function index(Request $request, Content $content)
    {
        $request_data = $request->all();

        $page_size = $request->input("per_page", self::PAGE_SIZE);
        $page = $request->input("page", 1);

        $condition = [];
        if (!empty($request_data['area_code'])) {
            $condition['area_code'] = $request_data['area_code'];
        }
        if (!empty($request_data['area_name'])) {
            $condition['area_name[~]'] = $request_data['area_name'];
        }

        $total = AdmDesignerArea::count($condition);

        $condition['ORDER'] = ['id' => 'DESC'];
        $condition['LIMIT'] = [
            ($page - 1) * $page_size,
            $page_size
        ];

        $lists = AdmDesignerArea::select('*', $condition);

        $gridModel = new pGridDataModel($lists, $total, [
            'perPage' => $page_size
        ]);

        $gridList = Admin::grid(
            $gridModel,
            function (Grid $grid) use ($gridModel) {
                $grid->paginate($gridModel->getPerPage());
                $grid->disableCreateButton();
                $grid->disableExport();
                $grid->disableRowSelector();

                $grid->filter(function (Grid\Filter $filter) {
                    $filter->disableIdFilter();
                    $filter->column(1/2, function ($filter) {
                        $filter->dropDown('area', [
                            'area_name' => '地区名称',
                            'area_code' => '地区code'
                        ]);
                    });
                    $filter->expand();
                });

//                $grid->column('id', '地区ID');
                $grid->column('area_code', '地区码');
                $grid->column('area_name', '地区');
                $grid->column('status', '状态')->display(function() {
                    return AdmDesignerArea::STATUS_TXT[$this->status];
                });
                $grid->column('switch', '开启状态')->switchToggle([
                    'on' => [
                        'value' => AdmDesignerArea::VIRTUAL_SWITCH_ON,
                        'text' => '开启'
                    ],
                    'off' => [
                        'value' => AdmDesignerArea::VIRTUAL_SWITCH_OFF,
                        'text' => '关闭'
                    ]
                ]);
                $grid->disableActions();
//                $grid->actions(function (Grid\Displayers\Actions $actions) {
//                    $actions->disableView();
//                });
            }
        );

        $tab = new Tab();
        $tab->add('虚拟手机号城市列表', $gridList->render());
        $content->row($tab);
        return $content
            ->header('虚拟手机号城市列表')
            ->description('')
            ->breadcrumb(['text' => '虚拟手机号城市列表']);
    }

    // 新增/修改地区信息
    public function edit(Request $request, Content $content, $id = 0) {
        $request = $request->all();

        if (!$id) {
            $is_create = true;
            $header = '新增';
        } else {
            $is_create = false;
            $header = '修改';
        }

        $tab = new Tab();
        $tab->add('地区信息', self::editAction($request, $id, $is_create));
        return $content->header($header)
            ->breadcrumb([
                'text' => '设计师地区',
                'url' => route('area.list')
            ], ['text' => $header])->row($tab);
    }

    public function editAction($request, $id = 0, $isCreate = false)
    {
        if ($isCreate) {
            $data = [];
            $form = new Form($data);
        } else {
            $data = AdmDesignerArea::get('*', ['id' => $id]);
            $form = new Form($data);
            $form->text('id', '地区ID')->setWidth(4, 2)->readOnly();
        }

        $form->text('area_name', '城市名称')
            ->setWidth(4, 2)
            ->required()
            ->help('请填写城市名，用于与设计师进行匹配，并显示在设计师列表页');
        $form->text('sort', '排序')
            ->setWidth(4, 2)
            ->required()
            ->help('顺序由小到大排序');
        $form->select('status', '状态')
            ->setWidth(4, 2)
            ->options(AdmDesignerArea::STATUS_TXT)
            ->default(AdmDesignerArea::STATUS_DELETE);
        $form->confirm('确定提交吗？');
        $form->action('/admin/Designer/area/save');
        return $form->render();
    }

    // 编辑奖项
    public function editSubmit(Request $request)
    {
        $request = $request->all();
        $data = [
            'area_name' => $request['area_name'],
            'sort' => $request['sort'],
            'adm_id' => Admin::user()->id,
            'status' => $request['status']
        ];
        if (isset($request['id'])) {
            $rs = AdmDesignerArea::update($data, ['id' => $request['id']]);
        } else {
            if (AdmDesignerArea::get('*', ['area_name' => $request['area_name']])) {
                $error = new MessageBag(['title' => '已经存在该地区']);
                return back()->with(compact('error'));
            }
            $rs = AdmDesignerArea::insert($data);
        }
        $title = isset($request['id']) ? '修改成功' : '添加成功';
        if ($rs === false) {
            $error = new MessageBag(['title' => $title]);
            return back()->with(compact('error'));
        }
        $this->resetCacheHotCity();
        $success = new MessageBag(['title' => $title]);
        return redirect('/admin/Designer/area')->with(compact('success'));
    }

    // 删除奖项
    public function del($id) {
        $area = AdmDesignerArea::get('*', ['id' => $id]);
        if ($area && !AdmDesignerArea::delete(['id' => $id])) {
            return response()->json([
                'status' => false,
                'message' => "操作失败",
            ]);
        }
        $this->resetCacheHotCity();
        return response()->json([
            'status' => true,
            'message' => "操作成功",
        ]);
    }

    public function resetCacheHotCity() {
        $HotAreas = AdmDesignerArea::getSortAreaList();
        $HotAreaList= [];
        foreach ($HotAreas as $hotArea) {
            $area_code = Region::getCodeByName($hotArea['area_name']);
            if ($area_code) {
            	$lid = Region::getOldCodeByCode($area_code);
                $HotAreaList[] = [
                    'lid' => $lid,
                    'city_name' => $hotArea['area_name'],
                ];
            }
        }
        if (!empty($HotAreaList)) {
            //DesignerArea::setValue('hot_city', $HotAreaList);
	        DesignerAreaRedis::setItem('hot_city', $HotAreaList);
        }
    }


    public function switch($id, Request $request)
    {
        $params = $request->all();

        $switch = $params['switch'] == 'on' ? 1: 0;

        $result = AdmDesignerArea::updateInfoById($id, [
            'switch' => $switch,
            'edittime' => time(),
            'adm_id' => Admin::user()->id
        ]);

        if ($result){
            return response()->json([
                'status' => true,
                'message' => "修改成功",
            ]);
        }else{
            return response()->json([
                'status' => false,
                'message' => "修改失败",
            ]);
        }
    }

}
